package com.btb.adapter.contract;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Uint;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.gas.StaticGasProvider;
import org.web3j.utils.Convert;

import com.btb.adapter.utils.Web3jUtils;

/**
 * 合约调用
 *
 * @author hqbzl
 */
@Service
public class PaymentService {
	@Autowired
	protected Web3j web3j;
//	@Autowired
//	protected Credentials credentials;
//	@Value("${adapter.contract.buy.address}")
//	private String contractBuyAddress;
	@Autowired
	private Payment payment;

	public TransactionReceipt buy(BigInteger weiValue, String orderID, BigInteger type, BigInteger orderTotalPrice) {
		try {
			return payment.buy(weiValue, orderID, type, orderTotalPrice).send();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	public String getBalance() {
		List<Type> response = payment.getBalanceEx();
		if (response.size() == 1) {
			String balance = new BigDecimal(((Uint) response.get(0)).getValue()).stripTrailingZeros().toPlainString();
			System.out.println(balance);
			return balance;
		}
		return StringUtils.EMPTY;
	}
}
